// map-picker.ts - 地图位置选择页面
interface LocationData {
  lng: number
  lat: number
}

interface AddressInfo {
  id?: string
  name: string
  address: string
  location?: LocationData
  distance?: number
  type?: string
}

interface PlaceItem {
  id: string
  name: string
  address: string
  location: LocationData
  distance?: number
  type?: string
}

Page({
  // 防抖定时器
  debounceTimer: null as any,
  // 搜索防抖定时器
  searchDebounceTimer: null as any,
  
  data: {
    // 状态栏高度
    statusBarHeight: '44px',
    
    // 地图配置
    mapKey: '2dec638f9508c079a4da1c7262ca67a',
    centerLocation: { lng: 116.397428, lat: 39.90923 }, // 地图中心点
    mapScale: 16,
    markers: [] as any[],
    
    // 搜索相关
    searchKeyword: '',
    currentCity: '', // 逆地理编码得到的城市名
    
    // 位置相关
    selectedAddress: null as AddressInfo | null,
    currentLocation: null as LocationData | null,
    nearbyPlaces: [] as PlaceItem[],
    
    // 页面状态
    fromPage: '',  // 来源页面
    locationType: ''  // 位置类型：start 或 end
  },

  /**
   * 页面卸载时清理定时器
   */
  onUnload() {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer)
    }
  },

  /**
   * 页面加载
   */
  onLoad(options: any) {
    // console.log('地图页面参数:', options)
    
    // 设置状态栏高度
    this.setStatusBarHeight()
    
    // 获取传入参数
    const fromPage = options.from || 'order'
    const locationType = options.type || 'start'
    
    this.setData({
      fromPage,
      locationType
    })
    
    // 初始化地图
    this.initMap()
    
    // 获取当前位置
    this.getCurrentLocation()
  },

  /**
   * 设置状态栏高度
   */
  setStatusBarHeight() {
    const windowInfo = (wx as any).getWindowInfo()
    const statusBarHeight = windowInfo.statusBarHeight || 44
    
    this.setData({
      statusBarHeight: statusBarHeight + 'px'
    })
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack()
  },

  /**
   * 初始化地图
   */
  initMap() {
    // 小程序内置地图组件不需要特殊初始化
    console.log('地图初始化完成')
  },

  /**
   * 获取当前位置
   */
  getCurrentLocation() {
    const that = this
    
    wx.getLocation({
      type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
      success(res) {
        // console.log('获取当前位置成功:', res)
        
        const location = {
          lng: res.longitude,
          lat: res.latitude
        }
        
        that.setData({
          currentLocation: location,
          centerLocation: location
        })
        
        // 获取当前位置地址信息
        that.reverseGeocode(location)
      },
      fail(err) {
        console.error('获取当前位置失败:', err)
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        })
        
        // 使用默认位置（北京）
        const defaultLocation = { lng: 116.397428, lat: 39.90923 }
        that.setData({
          currentLocation: defaultLocation,
          centerLocation: defaultLocation
        })
      }
    })
  },

  /**
   * 更新地图中心点
   */
  updateMapCenter(location: LocationData) {
    this.setData({
      centerLocation: location
    })
  },

  /**
   * 逆地理编码 - 根据坐标获取地址
   */
  reverseGeocode(location: LocationData) {
    const that = this
    const key = this.data.mapKey
    
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo',
      data: {
        key: key,
        location: `${location.lng},${location.lat}`,
        radius: 1000,
        extensions: 'all'
      },
      success(res: any) {
        // console.log('逆地理编码结果:', res.data)
        
        if (res.data.status === '1' && res.data.regeocode) {
          const regeocode = res.data.regeocode
          const formatted_address = regeocode.formatted_address
          const addressComponent = (regeocode as any).addressComponent || {}
          const cityName = addressComponent.city || addressComponent.district || addressComponent.province || ''
          
          const addressInfo: AddressInfo = {
            name: formatted_address,
            address: formatted_address,
            location: location
          }
          
          that.setData({
            selectedAddress: addressInfo,
            currentCity: cityName
          })
          
          // 获取附近地点
          if (regeocode.pois && regeocode.pois.length > 0) {
            const nearbyPlaces = regeocode.pois.slice(0, 10).map((poi: any, index: number) => ({
              id: poi.id || `poi_${index}`,
              name: poi.name,
              address: poi.address || formatted_address,
              location: {
                lng: parseFloat(poi.location.split(',')[0]),
                lat: parseFloat(poi.location.split(',')[1])
              },
              distance: poi.distance,
              type: that.getPlaceType(poi.type)
            }))
            
            that.setData({
              nearbyPlaces
            })
          }

          // 位置就绪后做一次默认搜索，验证 UI 展示
          try {
            that.setData({ searchKeyword: '医院' })
            that.searchLocation()
          } catch (e) {}
        }
      },
      fail(err) {
        console.error('逆地理编码失败:', err)
        wx.showToast({
          title: '获取地址失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 获取地点类型
   */
  getPlaceType(typeCode: string): string {
    if (typeCode && typeCode.includes('医院')) return 'hospital'
    if (typeCode && typeCode.includes('学校')) return 'school'
    return 'general'
  },

  /**
   * 搜索输入
   */
  onSearchInput(e: any) {
    this.setData({ searchKeyword: e.detail.value })

    // 输入长度>=2，500ms 防抖自动搜索
    if (this.searchDebounceTimer) {
      clearTimeout(this.searchDebounceTimer)
    }
    if ((e.detail.value || '').trim().length >= 2) {
      this.searchDebounceTimer = setTimeout(() => {
        try { console.log('触发自动搜索:', this.data.searchKeyword) } catch (e) {}
        this.searchLocation()
      }, 500)
    }
  },

  /**
   * 搜索位置
   */
  searchLocation() {
    const keyword = this.data.searchKeyword.trim()
    // 使用微信内置地点选择器，绕过第三方 WebService
    const that = this
    wx.chooseLocation({
      keyword: keyword || '',
      success(res) {
        // chooseLocation 返回 name/address/latitude/longitude
        const location = { lng: res.longitude, lat: res.latitude }
        const addressInfo: AddressInfo = {
          name: res.name || res.address,
          address: res.address || res.name || '',
          location
        }
        that.setData({
          selectedAddress: addressInfo,
          centerLocation: location,
          nearbyPlaces: [] // 收起悬浮面板
        })
        try { wx.showToast({ title: '已选择位置', icon: 'success' }) } catch (e) {}
      },
      fail(err) {
        console.log('选择位置取消/失败:', err)
      }
    })
  },

  /**
   * 选择地点
   */
  selectPlace(e: any) {
    const place = e.currentTarget.dataset.place as PlaceItem
    
    const addressInfo: AddressInfo = {
      id: place.id,
      name: place.name,
      address: place.address,
      location: place.location
    }
    
    this.setData({
      selectedAddress: addressInfo,
      // 选择后收起悬浮列表
      nearbyPlaces: []
    })
    
    // 更新地图中心点
    this.updateMapCenter(place.location)
    
    try { wx.vibrateShort({}) } catch (e) { console.log(e) }
  },

  /**
   * 关闭/清空搜索结果
   */
  clearSearchResults() {
    this.setData({ nearbyPlaces: [] })
  },

  /**
   * 刷新位置
   */
  refreshLocation() {
    if (this.data.currentLocation) {
      this.reverseGeocode(this.data.currentLocation)
    } else {
      this.getCurrentLocation()
    }
    
    try { wx.vibrateShort({}) } catch (e) { console.log(e) }
  },

  /**
   * 确认选择
   */
  confirmSelection() {
    const selectedAddress = this.data.selectedAddress
    if (!selectedAddress) {
      wx.showToast({
        title: '请先选择位置',
        icon: 'none'
      })
      return
    }
    
    // 将选择的位置信息传回上一页
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    if (prevPage) {
      const locationType = this.data.locationType
      
      if (locationType === 'start') {
        prevPage.setData({
          startLocation: selectedAddress.name || selectedAddress.address,
          startLocationData: selectedAddress
        })
      } else if (locationType === 'end') {
        prevPage.setData({
          endLocation: selectedAddress.name || selectedAddress.address,
          endLocationData: selectedAddress
        })
      }
      
      // 触发上一页的表单验证
      if (prevPage.validateForm) {
        prevPage.validateForm()
      }
    }
    
    wx.navigateBack({
      success: () => {
        wx.showToast({
          title: '位置选择成功',
          icon: 'success'
        })
      }
    })
  },

  /**
   * 地图移动事件（添加防抖）
   */
  onMapMove(e: any) {
    if (e.type === 'end') {
      const centerLocation = {
        lng: e.detail.centerLocation.longitude,
        lat: e.detail.centerLocation.latitude
      }
      
      this.setData({
        centerLocation
      })
      
      // 清除之前的定时器
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer)
      }
      
      // 设置新的定时器，800ms 后才执行逆地理编码
      this.debounceTimer = setTimeout(() => {
        this.reverseGeocode(centerLocation)
      }, 800)
    }
  },

  /**
   * 地图点击事件
   */
  onMapTap(e: any) {
    // console.log('地图点击:', e)
    if (e.detail.longitude && e.detail.latitude) {
      const location = {
        lng: e.detail.longitude,
        lat: e.detail.latitude
      }
      
      this.setData({
        centerLocation: location
      })
      
      this.reverseGeocode(location)
    }
  }
})
